<template>
  <a-card>
    <template #title>
      <a-form>
        <a-row :gutter="16">
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('订单编号')">
              <a-input v-model:value="page.loanRecordId"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('用户姓名')">
              <a-input v-model:value="page.name"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('手机号码')">
              <a-input v-model:value="page.phone"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :xs="24">
            <a-form-item :label="$t('订单状态')">
              <a-select v-model:value="page.orderStatus" allowClear>
                <a-select-option v-for="item in orderStatusList" :key="item.key" :value="item.key">{{
                    item.value
                  }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
<!--          <a-col :md="6" :xs="24">-->
<!--            <a-form-item :label="$t('钱包阶段')">-->
<!--              <a-select v-model:value="page.purseStatus" allowClear>-->
<!--                <a-select-option v-for="item in walletProgressList" :key="item.key" :value="item.key">{{-->
<!--                    item.value-->
<!--                  }}-->
<!--                </a-select-option>-->
<!--              </a-select>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :md="6" :xs="24" >
            <a-form-item :label="$t('注册渠道')">
              <a-select v-model:value="page.channel" allowClear>
                <a-select-option v-for="item in channelList" :key="item" :value="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :xs="24">
            <a-form-item :label="$t('申请时间')">
              <a-range-picker v-model:value="page.timeValue"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :xs="24">
            <a-form-item :label="$t('注册时间')">
              <a-range-picker v-model:value="page.registerTimeValue"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col style="text-align: right" :span="24">
            <a-button type="primary" @click="getTableData">{{ $t('查询') }}</a-button>
            <a-button style="margin-left: 10px" @click="resetSearch">{{ $t('重置') }}</a-button>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <a-table row-key="userId" :columns="tableColumn" :pagination="pagination" :data-source="tableData"
             :scroll="{x:1000}">
      <template #operation="{record }">
        <a-button type="link" @click="markUser(record)" v-show="isPermission('markers')">{{ $t('标记') }}</a-button>
        <a-button type="link" @click="sendMsg(record)" v-show="isPermission('sendSms')">{{ $t('发短信') }}</a-button>
        <a-button type="link" @click="sendEmail(record)" v-show="isPermission('sendEmail')">{{ $t('发送邮件') }}</a-button>
        <a-button type="link" @click="editPhone(record)" v-show="isPermission('updatePhone')">{{
            $t('编辑')
          }}
        </a-button>
        <a-button type="link" v-show="(record.orderStatus !== -1) && (record.orderStatus !== 0)" @click="lookPayDetails(record)">{{
            $t('支付详情')
          }}
        </a-button>
        <a-button type="link" v-show="(record.orderStatus !== -1) && (record.orderStatus !== 0)" @click="closeOrder(record)">{{
            $t('关闭订单')
          }}
        </a-button>
      </template>
      <template #failDescription="{record}">
        <a-tooltip placement="topLeft" :title="record.failDescription">
          <div style=" white-space: nowrap;overflow: hidden; text-overflow: ellipsis;"> {{
              record.failDescription
            }}
          </div>
        </a-tooltip>
      </template>
    </a-table>
    <a-modal v-model:visible="sendMsgVisible" :title="$t('发送短信')" @ok="confirmSendSms" :afterClose="clearSmsForm"
             @cancel="clearSmsForm">
      <a-form ref="sendSmsFormRef" :model="smsForm" :label-col="{span:4}">
        <a-form-item :label="$t('用户姓名')">
          <div style="line-height: 32px">
            {{ tableRows.name }}
          </div>
        </a-form-item>
        <a-form-item :label="$t('手机号')">
          <div style="line-height: 32px">
            {{ tableRows.phone }}
          </div>
        </a-form-item>
        <a-form-item :label="$t('短信内容')" name="smsContent" :rules="{
           required: true, message: $t('不能为空'), trigger: 'blur'
        }">
          <a-textarea v-model:value="smsForm.smsContent" :rows="4"/>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:visible="sendEmailVisible" :title="$t('发送邮件')" @ok="confirmSendEmail" :afterClose="clearEmailForm"
             @cancel="clearEmailForm">
      <a-form ref="sendEmailFormRef" :model="emailForm" :label-col="{span:4}">
        <a-form-item :label="$t('用户姓名')">
          <div style="line-height: 32px">
            {{ tableRows.name }}
          </div>
        </a-form-item>
        <a-form-item :label="$t('邮箱号')">
          <div style="line-height: 32px">
            {{ tableRows.mail }}
          </div>
        </a-form-item>
        <a-form-item :label="$t('标题')" name="subject" :rules="{
           required: true, message: $t('不能为空'), trigger: 'blur'
        }">
          <a-input v-model:value="emailForm.subject"/>
        </a-form-item>
        <a-form-item :label="$t('邮件内容')" name="text" :rules="{
           required: true, message: $t('不能为空'), trigger: 'blur'
        }">
          <a-textarea v-model:value="emailForm.text" :rows="4"/>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:visible="payDetailsVisible" :title="$t('支付详情')" :footer="null" @cancel="clearEmailForm">
      <a-table row-key="id"   :columns="payDetailsTableColumn" :data-source="payDetailsTableData" >
      </a-table>
    </a-modal>
  </a-card>
</template>

<script>
import {reactive, ref, toRefs, onMounted, computed, createVNode, shallowRef, onBeforeUnmount} from 'vue'
import {
  getOrderList,
  setMarkersOrder,
  orderSendSms,
  orderSendEmail,
  updateUserPhone,
  getPayDetails,
  orderClose
} from "../../../api/order"
import {message, Modal, Form, FormItem, Input, Button, Tooltip} from "ant-design-vue";
import locale from '@/locale'
import {useRouter} from "vue-router"
import '@wangeditor/editor/dist/css/style.css';
import {Editor, Toolbar} from '@wangeditor/editor-for-vue';
import {hasPermission, dateFormatTimeStamp,dateFormat} from '@/utils'
import {selectChannelList} from "../../../api";

const {t} = locale.global
const tableColumn = [
  {
    title: t('订单编号'),
    dataIndex: 'loanRecordId',
    width: 200,
    align: 'center',
    fixed: 'left',
    customRender: ({text, record, index}) => {
      const router = useRouter()
      if (hasPermission('OrderAgency', 'orderDetails')) {
        return record.orderStatus === 0 ? '' : createVNode('span', {
          style: {color: '#1890ff', cursor: 'pointer'},
          onClick: () => {
            router.push({
              path: '/order/orderDetails',
              query: {
                userId: record.userId,
                loanRecordId: text
              }
            })
          }
        }, text)
      } else {
        return record.orderStatus === 0 ? '' : text
      }
    }
  },
  {
    title: t('用户反馈'),
    dataIndex: 'isRead',
    width: 200,
    align: 'center',
    customRender: ({text, record, index}) => {
      if (text !== null && typeof text !== 'undefined') {
        const router = useRouter()
        return createVNode('span', {
          style: {color: text === 0 ?  '#ffc107' : '#1890ff', cursor: 'pointer'},
          onClick: () => {
            router.push({
              path: '/order/orderDetails',
              query: {
                userId: record.userId,
                loanRecordId: record.loanRecordId
              }
            })
          }
        }, text === 0 ? t('未读') : t('已读'))
      } else  {
        return  ''
      }
    }
  },
  {title: t('用户姓名'), dataIndex: 'name', width: 150, align: 'center'},
  {title: t('手机号码'), dataIndex: 'phone', width: 150, align: 'center',},
  {title: t('注册渠道'), dataIndex: 'channel', width: 150, align: 'center'},
  {title: t('注册时间'), dataIndex: 'createTime', width: 150, align: 'center'},
  {title: t('提现验证码'), dataIndex: 'code', width: 100, align: 'center',},
  {title: t('邮箱号'), dataIndex: 'mail', width: 150, align: 'center'},
  {
    title: t('申请时间'), dataIndex: 'loanTime', width: 200, align: 'center', customRender: ({text, record, index}) => {
      return record.orderStatus === 0 ? '' : text
    }
  },
  {title: t('申请金额'), dataIndex: 'loanAmount', width: 150, align: 'center'},
  {
    title: t('借款周期'), dataIndex: 'loanTerm', width: 150, align: 'center',  customRender: ({text, record, index}) => {
      return text ?  text + t('个月') : ''
    }
  },
  {
    title: t('订单状态'), dataIndex: 'orderStatus', width: 150, align: 'center', customRender: ({text, record, index}) => {
      const status = orderStatusList.find(item => item.key === text)
      return status ? status.value : '/'
    }
  },
  {
    title: t('付款阶段'),
    dataIndex: 'paymentStatus',
    width: 150,
    align: 'center',
    customRender: ({text, record, index}) => {
      const obj = {
        2: t('待付保证金'),
        3: t('已付保证金'),
        4: t('待付解冻费'),
        5: t('已付解冻费'),
        6: t('待付事故处理费'),
        7: t('已付事故处理费'),
        8: t('待付插队费'),
        9: t('已付插队费'),
      }
      return obj[text] || '/'
    }
  },
  {
    title: t('倒计时天数'),
    dataIndex: 'endDay',
    width: 100,
    align: 'center',
    customRender: ({text, record, index}) => {
      if (text) {
        // 结束时间
        const endDate = new Date((text * 86400000) + new Date().getTime())
        const endTimeStr = dateFormat(endDate, 'YYYY-mm-dd') + ' 00:00:00'
        // 结束时间戳
        const endTimeStamp = new Date(endTimeStr).getTime()
        const time = endTimeStamp - new Date().getTime()
        let day = Math.floor(time / (1000 * 60 * 60 * 24))
        let hour = Math.floor(time / (1000 * 60 * 60) % 24)  //计算小时数
        let minute = Math.floor(time / (1000 * 60) % 60)  //计算分钟数
        let second = Math.floor(time / 1000 % 60);
        return day + ' Días ' + hour + ':' + minute + ':' + second
      }
    }
  },
  {
    title: t('失败原因'),
    dataIndex: 'failDescription',
    width: 150,
    align: 'center',
    slots: {customRender: 'failDescription',}
  },
  {title: t('操作'), width: 200, align: 'center', fixed: 'right', slots: {customRender: 'operation',}},
]
const payDetailsTableColumn = [
  {title: t('创建时间'), dataIndex: 'createTime', align: 'center'},
  {title: t('支付订单号'), dataIndex: 'platformOrderId', align: 'center'},
  {
    title: t('支付状态'), dataIndex: 'status', align: 'center', customRender: ({text, record, index}) => {
      const obj = {
        0: t('已取消'),
        1: t('待支付'),
        2: t('已支付'),
      }
      return obj[text]
    }
  },
]
const orderStatusList = [
  {key: 0, value: t('未申请')},
  {key: 1, value: t('审核中')},
  {key: 3, value: t('待放款')},
  {key: 4, value: t('放款中')},
  {key: 5, value: t('放款失败')},
  {key: -12, value: t('已放款')},
]
const walletProgressList = [
  {key: 1, value: t('可提现保证金')},
  {key: 2, value: t('待发起提现')},
  {key: 3, value: t('已发起提现')},
  {key: 4, value: t('已提现保证金')},
]
export default {
  name: "OrderAgency",
  components: {Editor, Toolbar},
  setup() {
    const sendSmsFormRef = ref(null)
    const sendEmailFormRef = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableRows: {},
      sendMsgVisible: false,
      tableData: [],
      smsForm: {
        smsContent: null,
      },
      emailForm: {
        subject: null,
        text: null
      },
      sendEmailVisible: false,
      payDetailsVisible: false,
      payDetailsTableData: [],
      channelList:[]
    })
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total,
      onChange: (page) => {
        state.page.pageNum = page
        method.getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        method.getTableData()
      }
    }))
    const method = {
      async getTableData() {
        const [createTimeStart,createTImeEnd] = dateFormatTimeStamp(state.page.registerTimeValue || [])
        const [startLoanTime, endLoanTime] = dateFormatTimeStamp(state.page.timeValue || [])
        const params = {
          createTimeStart,createTImeEnd,
          startLoanTime, endLoanTime,
          ...state.page, pageType: 2
        }
        delete params.timeValue
        delete params.registerTimeValue
        const res = await getOrderList(params)
        if (res.code === 1) {
          const {list, total} = res.data
          state.tableData = list
          state.page.total = total
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        method.getTableData()
      },
      markUser(record) {
        Modal.confirm({
          title: () => record.name + ' - ' + t('标记为重点客户'),
          content: t('标记后,当前客户将流入重点待办列表，请确认是否标记'),
          async onOk() {
            const res = await setMarkersOrder({
              loanRecordId: record.loanRecordId,
              markersStatus: 1
            })
            if (res.code === 1) {
              message.success(t('操作成功'))
              method.getTableData()
            }
          },
          onCancel() {
            console.log('Cancel');
          },
        });
      },
      sendMsg(record) {
        state.sendMsgVisible = true;
        state.tableRows = {...record}
      },
      sendEmail(record) {
        state.sendEmailVisible = true;
        state.tableRows = {...record}
      },
      confirmSendEmail() {
        sendEmailFormRef.value.validate().then(async () => {
          const formData = new FormData()
          formData.append('toEmail', state.tableRows.mail)
          formData.append('text', state.emailForm.text)
          formData.append('subject', state.emailForm.subject)
          const res = await orderSendEmail(formData)
          if (res.code === 1) {
            message.success(t('发送成功'))
            method.getTableData()
            state.sendEmailVisible = false
          }
        })
      },
      clearEmailForm() {
        state.emailForm.text = null
        state.emailForm.subject = null
        sendEmailFormRef.value.resetFields()
      },
      editPhone({userId, phone}) {
        let textPhone = phone
        Modal.confirm({
          title: t('编辑手机号'),
          content: createVNode(Input, {
            defaultValue: phone,
            maxLength: 10,
            onInput: (value) => {
              textPhone = value.target.value
            },
            onKeyup: (value) =>{
              value.target.value = value.target.value.replace(/[^\d]/g, '')
            }
          }),
          async onOk() {
            if (textPhone.length !== 10) {
              message.error(t('手机号格式错误'))
              return Promise.reject()
            }
            const res = await updateUserPhone({
              id: userId, phone: textPhone
            })
            if (res.code === 1) {
              message.success(t('操作成功'))
              method.getTableData()
            }
          },
        });
      },
     async closeOrder(record) {
       Modal.confirm({
         title: () => record.name + ' - ' + t('关闭订单'),
         content: t('请确认是否关闭该订单'),
         async onOk() {
           const res  = await orderClose({  loanRecordId: record.loanRecordId,})
           if (res.code === 1) {
             message.success(t('操作成功'))
             method.getTableData()
           }
         },
       });
      },
      confirmSendSms() {
        sendSmsFormRef.value.validate().then(async () => {
          const res = await orderSendSms({
            phone: state.tableRows.phone,
            text: state.smsForm.smsContent
          })
          if (res.code === 1) {
            message.success(t('发送成功'))
            method.getTableData()
            state.sendMsgVisible = false
          }
        })
      },
      async lookPayDetails({loanRecordId}) {
        const res = await getPayDetails({
          orderId: loanRecordId
        })
        if (res.code === 1) {
          state.payDetailsTableData = res.data
          state.payDetailsVisible = true
        }
      },
      clearSmsForm() {
        state.smsForm.smsContent = null
        sendSmsFormRef.value.resetFields()
      },
      isPermission(value) {
        return hasPermission('OrderAgency', value)
      }
    }
    onMounted(() => {
      method.getTableData()
      selectChannelList().then(res => {
        state.channelList = res.data
      })
    })
    return {
      payDetailsTableColumn,
      walletProgressList,
      orderStatusList,
      tableColumn,
      sendSmsFormRef,
      sendEmailFormRef,
      pagination,
      ...method,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
